import moment from 'moment';
import * as notifyRecordModel from '../../models/notify_record';
import * as bookAlbumModel from '../../models/book_album';
import { ValidException } from '../../helps/exception';

export function* aggregation({ type, robot_id }) {
  if (!robot_id) throw ValidException('Robot参数错误');
  if (type !== 'spell' && type !== 'read') throw ValidException('类型错误：spell、read');
  let list = yield notifyRecordModel.aggregation(robot_id, type);
  return list;
}

export function* topList({ type, module, top, robot_id }) {
  if (!robot_id) throw ValidException('Robot参数错误');
  if (type !== 'spell' && type !== 'read') throw ValidException('类型错误：spell、read');
  if (type === 'spell') {
    if (module !== 'letter' && module !== 'word') throw ValidException('spell模块错误：letter，word');
  } else if (type === 'read') {
    if (module !== 'book_album') throw ValidException('read模块错误：book_album');
  }
  let list = yield notifyRecordModel.top(robot_id, type, module, top);
  if (list.length === 0) return list;
  let ids = list.map(row => row.module_id);
  let realModel = null;
  switch (module) {
    case 'book_album':
      realModel = bookAlbumModel;
      break;
    default:
  }
  let model_list = yield realModel.getIds(ids);
  let map = {};
  model_list.forEach((row) => {
    map[row.id] = row;
  });
  list = list.map((row) => {
    row.info = map[row.module_id];
    return row;
  });
  return list;
}

export function* week({ type, robot_id }) {
  if (!robot_id) throw ValidException('Robot参数错误');
  if (type !== 'spell' && type !== 'read') throw ValidException('类型错误：spell、read');
  let start_time = new Date(moment().subtract(7, 'days').toISOString());
  let end_time = new Date();
  let list = yield notifyRecordModel.day(robot_id, type, start_time, end_time);
  return list;
}
